package com.ruoyi.manage.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.manage.domain.CrStudentProfile;
import com.ruoyi.manage.service.ICrStudentProfileService;

/**
 * 学生个人资料Controller
 * 
 * @author ruoyi
 * @date 2024-01-20
 */
@RestController
@RequestMapping("/campus/student/profiles")
public class CrStudentProfileController extends BaseController
{
    @Autowired
    private ICrStudentProfileService studentProfileService;

    /**
     * 获取当前登录学生个人资料
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/current")
    public AjaxResult getCurrentStudentProfile()
    {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = loginUser.getUserId();
            
            CrStudentProfile profile = studentProfileService.selectCrStudentProfileByUserId(userId);
            if (profile == null) {
                // If no profile exists, create a default one
                profile = new CrStudentProfile();
                profile.setUserId(userId);
                profile.setRealName(loginUser.getUser().getNickName());
                profile.setStudentNo("未设置");
                profile.setMajor("未设置");
                profile.setGrade("未设置");
                profile.setCollege("未设置");
                profile.setClassName("未设置");
                profile.setSkills("");
                profile.setInterests("");
                profile.setSelfIntroduction("暂无简介");
                studentProfileService.insertCrStudentProfile(profile);
            }
            return success(profile);
        } catch (Exception e) {
            logger.error("获取学生个人资料失败: " + e.getMessage());
            return error("获取个人资料失败");
        }
    }

    /**
     * 获取指定学生个人资料 (学生专用接口)
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/{studentId}")
    public AjaxResult getStudentProfile(@PathVariable("studentId") Long studentId)
    {
        try {
            // 验证学生只能访问自己的资料
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (!loginUser.getUserId().equals(studentId)) {
                return error("无权限访问其他学生的个人资料");
            }
            
            CrStudentProfile profile = studentProfileService.selectCrStudentProfileByUserId(studentId);
            if (profile == null) {
                // If no profile exists, create a default one
                profile = new CrStudentProfile();
                profile.setUserId(studentId);
                profile.setRealName(loginUser.getUser().getNickName());
                profile.setStudentNo("未设置");
                profile.setMajor("未设置");
                profile.setGrade("未设置");
                profile.setCollege("未设置");
                profile.setClassName("未设置");
                profile.setSkills("");
                profile.setInterests("");
                profile.setSelfIntroduction("暂无简介");
                studentProfileService.insertCrStudentProfile(profile);
            }
            return success(profile);
        } catch (Exception e) {
            logger.error("获取学生个人资料失败: " + e.getMessage());
            return error("获取个人资料失败");
        }
    }

    /**
     * 更新学生个人资料
     */
    @PreAuthorize("@ss.hasRole('student')")
    @Log(title = "学生个人资料", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody CrStudentProfile studentProfile)
    {
        logger.info("开始更新学生个人资料，用户ID: {}", studentProfile.getUserId());
        try {
            // 验证学生只能更新自己的资料
            LoginUser loginUser = SecurityUtils.getLoginUser();
            logger.info("当前登录用户ID: {}", loginUser.getUserId());
            
            if (!loginUser.getUserId().equals(studentProfile.getUserId())) {
                logger.warn("权限验证失败: 用户 {} 尝试更新用户 {} 的资料", 
                           loginUser.getUserId(), studentProfile.getUserId());
                return error("无权限更新其他学生的个人资料");
            }
            
            // 处理技能和兴趣爱好字段，确保它们是有效的JSON字符串
            String skills = studentProfile.getSkills();
            String interests = studentProfile.getInterests();
            
            logger.info("原始skills字段: {}", skills);
            logger.info("原始interests字段: {}", interests);
            
            // 修复skills字段格式
            if (skills != null) {
                // 如果字符串不是有效的JSON格式，尝试修正
                if (!skills.trim().startsWith("[") || !skills.trim().endsWith("]")) {
                    // 移除可能存在的非法字符和多余内容
                    skills = skills.replaceAll(",[^\\[\\]]+", "");
                    if (!skills.trim().startsWith("[")) {
                        skills = "[\"" + skills.replace(",", "\",\"").replace("\"", "") + "\"]";
                    }
                }
                studentProfile.setSkills(skills);
            } else {
                studentProfile.setSkills("[]");
            }
            
            // 修复interests字段格式
            if (interests != null) {
                // 如果字符串不是有效的JSON格式，尝试修正
                if (!interests.trim().startsWith("[") || !interests.trim().endsWith("]")) {
                    // 移除可能存在的非法字符和多余内容
                    interests = interests.replaceAll(",[^\\[\\]]+", "");
                    if (!interests.trim().startsWith("[")) {
                        interests = "[\"" + interests.replace(",", "\",\"").replace("\"", "") + "\"]";
                    }
                }
                studentProfile.setInterests(interests);
            } else {
                studentProfile.setInterests("[]");
            }
            
            logger.info("处理后的skills字段: {}", studentProfile.getSkills());
            logger.info("处理后的interests字段: {}", studentProfile.getInterests());
            
            // 检查资料是否存在
            CrStudentProfile existingProfile = studentProfileService.selectCrStudentProfileByUserId(studentProfile.getUserId());
            if (existingProfile == null) {
                logger.info("用户 {} 的个人资料不存在，将创建新记录", studentProfile.getUserId());
                // 设置profileId为null，让数据库自动生成
                studentProfile.setProfileId(null);
                int insertResult = studentProfileService.insertCrStudentProfile(studentProfile);
                if (insertResult > 0) {
                    logger.info("创建个人资料成功");
                    return success("个人资料创建成功");
                } else {
                    logger.error("创建个人资料失败");
                    return error("创建个人资料失败");
                }
            }
            
            // 更新现有资料
            logger.info("更新用户 {} 的个人资料", studentProfile.getUserId());
            studentProfile.setProfileId(existingProfile.getProfileId()); // 确保使用正确的profileId
            int result = studentProfileService.updateCrStudentProfile(studentProfile);
            if (result > 0) {
                logger.info("个人资料更新成功");
                return success("个人资料更新成功");
            } else {
                logger.error("个人资料更新失败，影响行数为0");
                return error("个人资料更新失败，可能数据没有变化");
            }
        } catch (Exception e) {
            logger.error("更新学生个人资料失败: " + e.getMessage(), e);
            return error("更新个人资料失败: " + e.getMessage());
        }
    }
}